using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using CustomLitJson;
using System.Threading.Tasks;
using Sirenix.OdinInspector;


[Api]
public static class CloundSaveApi 
{
    public static string secret = "szf5fo0nah2uwi3xc4xeuwiph6rcz2wz";

    public static string Sign(string uid, string nonce, string body)
    {
        var signSource = $"{uid}{nonce}{body}";
        var signatrue = SecurityUtil.ComputeHMACSHA1(signSource, secret);
        return signatrue;
    }

    public class RpcResponse
    {
        public int code;
        public string data;

        public bool IsSuccess
        {
            get
            {
                if (code == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public string ErrorMsg
        {
            get
            {
                if (!this.IsSuccess)
                {
                    return data;
                }
                else
                {
                    return "";
                }
            }
        }
    }


    public static async Task<bool> SaveAsync(string uid, string content)
    {
        var baseUrl = CwManager.Stuff.data.baseUrl;
        var api = "game/yyds/set";
        var nonce = "a";
        var body = content;
        var signatrue = Sign(uid, nonce, body);
        var url = $"{baseUrl}/{api}?uid={uid}&nonce={nonce}&signature={signatrue}";
        var responseJson = await HttpUtil.RequestTextAsync(url, HttpMethod.Post, body, HttpUtil.ContentType.Plain);
        var response = JsonMapper.Instance.ToObject<RpcResponse>(responseJson);
        if (!response.IsSuccess)
        {
            Debug.Log("[CloundSave] save fail, error msg: " + response.ErrorMsg);
            return false;
        }
        else
        {
            Debug.Log("[CloundSave] save success");
            return true;
        }
    }
     
 
    public static async Task<string> RequestAsync(string uid)
    {
        var baseUrl = CwManager.Stuff.data.baseUrl;
        var api = "game/yyds/get";
        var nonce = "a";
        var body = "";
        var signatrue = Sign(uid, nonce, body);
        var url = $"{baseUrl}/{api}?uid={uid}&nonce={nonce}&signature={signatrue}";
        var responseString = await HttpUtil.RequestTextAsync(url, HttpMethod.Post, body, HttpUtil.ContentType.Plain);
        return responseString;
    }
}
